package com.changgou.pay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.pay.service.WxPayService;
import com.changgou.util.ConvertUtils;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wxpay")
public class WxPayController {


    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 下单
     * @param orderId
     * @param money
     * @return
     */
    @GetMapping("/nativePay")
    public Result nativePay(String orderId, Integer money) {
        Map map = wxPayService.nativePay(orderId, money);
        return new Result(true, StatusCode.OK, "调用成功", map);
    }

    /**
     * 支付通知
     */
    @RequestMapping("/notify")
    public void notifyLogic(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("调用了支付通知");

        try {
            String xml = ConvertUtils.convertToString(request.getInputStream());
            System.out.println(xml);
            Map<String, String> map = WXPayUtil.xmlToMap(xml);

            //如果通知的结果是成功
            if ("SUCCESS".equals(map.get("result_code"))) {

                //不放心结果是不是伪造，所以要主动查询
                Map queryMap = wxPayService.queryOrder(map.get("out_trade_no"));
                if (queryMap == null) {
                    return;
                }

                //真正的成功
                if ("SUCCESS".equals(queryMap.get("result_code"))) {
                    // 修改订单状态
                    Map payMap = new HashMap();
                    payMap.put("orderId", map.get("out_trade_no"));
                    payMap.put("transactionId", map.get("transaction_id"));

                    //发送到mq
                    rabbitTemplate.convertAndSend("", "order_pay", JSON.toJSONString(payMap));

                    //通知页面
                    rabbitTemplate.convertAndSend("paynotify", "", map.get("out_trade_no"));
                    response.setContentType("text/xml");
                    response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
                } else {
                    //控制台打印错误描述
                    System.out.println(queryMap.get("err_code_des"));
                }

            }


        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭订单
     * @param orderId
     * @return
     */
    @PutMapping("/close/{orderId}")
    public Result closeOrder(@PathVariable String orderId){
        Map map = wxPayService.closeOrder( orderId );
        return new Result( true,StatusCode.OK,"",map );
    }

    /**
     * 查询订单
     * @param orderId
     * @return
     */
    @GetMapping("/query/{orderId}")
    public Result queryOrder(@PathVariable String orderId){
        Map map = wxPayService.queryOrder( orderId );
        return new Result( true,StatusCode.OK,"",map );
    }

}
